<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
  <link rel="stylesheet" href="../css/clock.css">
  <title>炫酷时钟</title>
</head>
<body id="body">
<div class="bgColor">
  <div class="color"><i class="layui-icon layui-icon-theme"></i>我想换个背景 </div>
  <span id="color"></span>
</div>

<h2 class="timeTitle">the time is now</h2>
<div id="clock">
  <div id="time">
    <div><span id="hour">00</span><span>Hours</span></div>
    <div><span id="minute">00</span><span>Minutes</span></div>
    <div><span id="second">00</span><span>Seconds</span></div>
    </div>
  </div>
<script src="../lib/layui-v2.6.3/layui.js" type="text/javascript" charset="utf-8"></script>
<script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  // “我想换个背景”点击事件
  $("#color > div").on('click',function(){
    return false;
  });

  $(".color").on('click',function(){
    $("#color > div").click();
      return false;
  });

  var body = document.getElementById('body');

  //获取本地时间
  function clock(){
    let hours = document.getElementById('hour');
    let minutes = document.getElementById('minute');
    let seconds = document.getElementById('second');

    let date = new Date();

    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();

    if(h < 10){
      h = '0' + h;
    }
    if(m < 10){
      m = '0' + m;
    }
    if (s < 10){
      s = '0' + s;
    }

    hours.innerHTML = h;
    minutes.innerHTML = m;
    seconds.innerHTML = s;
  }

  setInterval(clock,1000);

  // 将颜色值存放在localStorage中
  var data = layui.data('bgcolor');
  if(data['color'] != null){
    body.style.background = data['color'];
  }

  //字体颜色取反
  var bgColor = $(".bgColor");
  var timeTitle = $(".timeTitle");
  function fontColor(oldColor){
    var OldColorValue = "0x"+oldColor.replace(/#/g,"");
    var newColor = "#"+(0xFFFFFF-OldColorValue).toString(16);
    bgColor.css("color",newColor);
    timeTitle.css("color",newColor);
  }

  // 判断是否按下对应按键，隐藏和显示相关内容
  document.onkeydown=function(event){
    if(event.keyCode==81){
      bgColor.css("opacity","0");
    }
  };
  document.onkeyup=function(event){
    if(event.keyCode==87){
      bgColor.css("opacity","1");
    }
  };


  //调色板
  layui.use('colorpicker', function(){
    var colorpicker = layui.colorpicker;
    var $ = layui.$;
    //渲染
    colorpicker.render({
      elem: '#color',  //绑定元素
      done: function(color){
        $("body").css("background",color);
        fontColor(color);
        layui.data('bgcolor', {
          key: 'color',
          value: color
        });
      }
    });
    $("#color > div").css("opacity","0");
  });
</script>
</body>
</html>
